import React, { useState, useEffect, useCallback, useRef } from 'react';
import { DatePicker, Spin } from 'antd';
import { Line } from '@ant-design/charts';
import moment from 'moment';
import { flatTryCatch } from '../../../servers/http';
import { homeAllStatistic } from 'admin/servers/servers';

const { RangePicker } = DatePicker;

const nameMap = {
  hangduanSendNumber: '行业短信',
  fenceSendNumber: '靶向短信',
  callTotalTalkTime: '智能外呼',
};

const SecondStatistic: React.FC = () => {
  // 参数
  const [momentRange, setMomentRange] = useState<any>([
    moment().startOf('week'),
    moment().endOf('week'),
  ]);
  const [loading, setLoading] = useState(false);

  // 数据
  const [statisticData, setStatisticData] = useState<any>({
    data: [],
    xField: 'date',
    yField: 'value',
    seriesField: 'type',
    yAxis: {
      label: { formatter: v => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') },
    },
    color: ['#1890ff', '#69c0ff', '#096dd9'],
    lineStyle: { lineWidth: 2 },
    point: { size: 4, shape: 'circle' },
    tooltip: { shared: true },
    legend: { position: 'top' },
    smooth: false, // 直线
    animation: false, // 关键修复：禁用动画
    autoFit: true, // 开启自动适应
  });

  // 处理数据
  const handleData = useCallback((allData: any) => {
    // 转成[key, value]，key就是三个项目名字，value是数据
    // value再转需要的格式
    // 最后是一个二维数组，用flatMap转成一维的
    const statisticalData = Object.entries(allData)
      .map(([key, value]: any) =>
        value.map(({ time, value }) => ({
          date: time,
          type: nameMap[key],
          value,
        }))
      )
      .flatMap(item => item);

    setStatisticData(prev => ({
      ...prev,
      data: statisticalData,
    }));
  }, []);

  // 请求数据
  const fetchData = useCallback(async () => {
    if (!momentRange || !momentRange.length) return;

    const params = {
      beginTime: momentRange[0].format('YYYY-MM-DD'),
      endTime: momentRange[1].format('YYYY-MM-DD'),
    };
    setLoading(true);
    const { response, error } = await flatTryCatch(homeAllStatistic(params));
    setLoading(false);
    if (error) return;
    handleData(response.data);
  }, [handleData, momentRange]);

  // 加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 处理时间范围变化
  const handleRangeChange = (dates, dateStrings) => {
    setMomentRange(dates);
  };

  // 图表自适应
  const chartRef = useRef<any>(null);
  // useEffect(() => {
  //   const handleResize = () => {
  //     if (chartRef.current) {
  //       chartRef.current.chart.forceFit(); // 强制重新适应
  //     }
  //   };

  //   window.addEventListener('resize', handleResize);
  //   return () => {
  //     window.removeEventListener('resize', handleResize);
  //   };
  // }, []);

  return (
    <div className="single-item statistical-data">
      <div className="single-title-wrapper">
        <div className="single-title">统计数据</div>
        <RangePicker
          allowClear={false}
          value={momentRange}
          onChange={handleRangeChange}
          format="YYYY-MM-DD"
        />
      </div>
      <Spin spinning={loading}>
        <Line {...statisticData} style={{ height: '400px' }} chartRef={chartRef} />
      </Spin>
    </div>
  );
};

export default SecondStatistic;
